package com.zyy.game.tianlong.network.codec;

import com.alibaba.fastjson.JSON;
import com.zyy.game.tianlong.network.GameContext;
import com.zyy.game.tianlong.network.SocketMsg;
import com.zyy.game.tianlong.network.callback.GlobalExceptionCallBack;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.ReferenceCountUtil;

/**
 * 解码器 将二进制转换为{@link SocketMsg}对象
 *
 * @author relufi
 * @date 2019/7/22 0022 10:23
 */
@ChannelHandler.Sharable
public class GameWebSocketDecoder extends ChannelInboundHandlerAdapter {
    private final GlobalExceptionCallBack globalExceptionCallBack;

    public GameWebSocketDecoder(GlobalExceptionCallBack globalExceptionCallBack) {
        this.globalExceptionCallBack = globalExceptionCallBack;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            if (msg instanceof TextWebSocketFrame) {
                TextWebSocketFrame text = (TextWebSocketFrame) msg;
                ctx.fireChannelRead(JSON.parseObject(text.text(), SocketMsg.class));
            } else if (!(msg instanceof DefaultFullHttpRequest)) {
                ctx.close();
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        globalExceptionCallBack.exceptionCaught(new GameContext(ctx), cause);
    }
}
